package com.springdemo.spring5.dao;

import com.springdemo.spring5.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.Arrays;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: zjz
 * Date: 2022/02/28 15:31
 * Description:
 * Version: V1.0
 */
@Repository
public class UserDaoImpl implements UserDao{
    //注入JdbcTemplate
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Override
    public void add(User user) {
        //1 创建sql语句
        String sql="insert into t_user values(null ,?,?)";
        //2 调用方法实现
        Object[] args={user.getUsername(), user.getUstatus()};
        int update = jdbcTemplate.update(sql, args);
        System.out.println(update);
    }

    @Override
    public void delete(int id) {
        String sql="delete from t_user where user_id=?";
        int update = jdbcTemplate.update(sql, id);
        System.out.println(update);
    }

    @Override
    public void update(User user) {
        String sql="update t_user set username=?,ustatus=? where user_id=?";
        Object[] args={user.getUsername(),user.getUstatus(),user.getUserId()};
        int update = jdbcTemplate.update(sql, args);
        System.out.println(update);
    }

    @Override
    public int count() {
        String sql ="select count(*) from t_user";
        Integer count = jdbcTemplate.queryForObject(sql, Integer.class);
        return count;
    }

    @Override
    public User UserInfo(int id) {
        String sql="select * from t_user where user_id=?";
        //调用方法
        User user = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<User>(User.class), id);
        return user;
    }

    @Override
    public List<User> all() {
        String sql="select * from t_user";
        List<User> userList = jdbcTemplate.query(sql, new BeanPropertyRowMapper<User>(User.class));
        return userList;
    }

    @Override
    public void batchAdd(List<Object[]> batchList) {
        String sql="insert into t_user values(null,?,?)";
        int[] ints = jdbcTemplate.batchUpdate(sql, batchList);//返回影响的行数
        System.out.println(Arrays.toString(ints));
    }

    @Override
    public void batchUpdate(List<Object[]> batchList) {
        String sql="update t_user set username=?,ustatus=? where user_id=?";
        int[] ints = jdbcTemplate.batchUpdate(sql, batchList);
        System.out.println(Arrays.toString(ints));
    }

    @Override
    public void batchDelete(List<Object[]> batchList) {
        String sql="delete from t_user where user_id=?";
        int[] ints = jdbcTemplate.batchUpdate(sql, batchList);
        System.out.println(Arrays.toString(ints));
    }


}
